import json

from django_redis import get_redis_connection

from utils.cookiesecret import CookieSecret


def merge_cart_cookie_to_redis(request, response):
    # 取cookie数据
    cookie_str = request.COOKIES.get("carts")
    user = request.user
    # 链接数据库
    redis_client = get_redis_connection("carts")
    if cookie_str:
        # update可以覆盖两个字典   写可查一下
        cookie_cart_dict = CookieSecret.loads(cookie_str)
        for sku_id in cookie_cart_dict:
            sku_dict = cookie_cart_dict[sku_id]
            redis_client.hset(user.id,sku_id,json.dumps(sku_dict))

        # 删除cookie
        response.delete_cookie("carts")

